其他
从零搭建一个 Spring Boot 开发环境!Spring Boot+Mybatis+Swagger2 环境搭建
点击上方 Java后端,选择 设为星标
作者 | calebman
链接 | www.jianshu.com/p/95946d6b0c7d
本文简介
为什么使用Spring Boot 搭建怎样一个环境 开发环境 导入快速启动项目 集成前准备 集成Mybatis 集成Swagger2 多环境配置 多环境下的日志配置 常用配置
为什么使用Spring Boot
搭建怎样一个环境
开发环境
导入快速启动项目
集成前准备
修改.properties为.yml
对于键的描述由原有的 "." 分割变成了树的形状 对于所有的键的后面一个要跟一个空格,不然启动项目会报配置解析错误
# properties式语法描述
spring.datasource.name = mysql
spring.datasource.url = jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123
# yml式语法描述
spring:
datasource:
name: mysql
url: jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username: root
password: 123
配置所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
集成Mybatis
配置druid数据库连接池
spring:
datasource:
# 如果存在多个数据源,监控的时候可以通过名字来区分开来
name: mysql
# 连接数据库的url
url: jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
# 连接数据库的账号
username: root
# 连接数据库的密码
password: 123
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
# 扩展插件
# 监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
filters: stat
# 最大连接池数量
maxActive: 20
# 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
initialSize: 1
# 获取连接时最大等待时间,单位毫秒
maxWait: 60000
# 最小连接池数量
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
# 连接保持空闲而不被驱逐的最长时间
minEvictableIdleTimeMillis: 300000
# 用来检测连接是否有效的sql,要求是一个查询语句
# 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用
validationQuery: select count(1) from 'table'
# 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
testWhileIdle: true
# 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnBorrow: false
# 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnReturn: false
# 是否缓存preparedStatement,即PSCache
poolPreparedStatements: false
# 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true
maxOpenPreparedStatements: -1
配置pagehelper分页插件
# pagehelper分页插件
pagehelper:
# 数据库的方言
helperDialect: mysql
# 启用合理化,如果pageNum < 1会查询第一页,如果pageNum > pages会查询最后一页
reasonable: true
代码逆向生成插件mybatis-generator的配置及运行
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="generator/generator.properties"/>
<classPathEntry location="${classPathEntry}"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/${db}?characterEncoding=utf-8"
userId="${userId}"
password="${password}">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<javaModelGenerator targetPackage="${pojoTargetPackage}" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="${mapperTargetPackage}" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="${daoTargetPackage}" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="%" schema="${db}"/>
</context>
</generatorConfiguration>
在generatorConfig.xml同级创建generator.properties文件,现只需要配置generator.properties文件即可,配置内容如下
# 请手动配置以下选项
# 数据库驱动:选择你的本地硬盘上面的数据库驱动包
classPathEntry = D:/CJH/maven-repository/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar
# 数据库名称、用户名、密码
db = db
userId = root
password = 123
# 生成pojo的包名位置 在src/main/java目录下
pojoTargetPackage = com.spring.demo.springbootexample.mybatis.po
# 生成DAO的包名位置 在src/main/java目录下
daoTargetPackage = com.spring.demo.springbootexample.mybatis.mapper
# 生成Mapper的包名位置 位于src/main/resources目录下
mapperTargetPackage = mapper
3. 运行mybatis-generator插件生成Dao、Model、Mapping
cd到项目pom.xml同级目录运行以下命令
mvn mybatis-generator:generate -e
打开命令行mybatis扫描包配置
mybatis:
# mapper.xml包地址
mapper-locations: classpath:mapper/*.xml
# pojo生成包地址
type-aliases-package: com.spring.demo.springbootexample.mybatis.po
2. 在SpringBootExampleApplication.java中开启Mapper扫描注解
@SpringBootApplication
@MapperScan("com.spring.demo.springbootexample.mybatis.mapper")
public class SpringBootExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootExampleApplication.class, args);
}
}
测试mapper的有效性
@Controller
public class TestController {
@Autowired
UserMapper userMapper;
@RequestMapping("/test")
@ResponseBody
public Object test(){
return userMapper.selectByExample(null);
}
}
Tomcat started on port(s): 8080 (http) with context path ''
http://localhost:8080/test
集成Swagger2
public class SwaggerConfig {
private final String version = "1.0";
private final String title = "SpringBoot示例工程";
private final String description = "API文档自动生成示例";
private final String termsOfServiceUrl = "http://www.kingeid.com";
private final String license = "MIT";
private final String licenseUrl = "https://mit-license.org/";
private final Contact contact = new Contact("calebman", "https://github.com/calebman", "chenjianhui0428@gmail.com");
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInf())
.select().build();
}
private ApiInfo buildApiInf() {
return new ApiInfoBuilder().title(title).termsOfServiceUrl(termsOfServiceUrl).description(description)
.version(version).license(license).licenseUrl(licenseUrl).contact(contact).build();
}
}
@Controller
@RequestMapping("/v1/product")
@Api(value = "DocController", tags = {"restful api示例"})
public class DocController extends BaseController {
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseBody
@ApiOperation(value = "修改指定产品", httpMethod = "PUT", produces = "application/json")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "产品ID", required = true, paramType = "path")})
public WebResult update(@PathVariable("id") Integer id, @ModelAttribute Product product) {
logger.debug("修改指定产品接收产品id与产品信息=>%d,{}", id, product);
if (id == null || "".equals(id)) {
logger.debug("产品id不能为空");
return WebResult.error(ERRORDetail.RC_0101001);
}
return WebResult.success();
}
}
@ApiModel(value = "产品信息")
public class Product {
@ApiModelProperty(required = true, name = "name", value = "产品名称", dataType = "query")
private String name;
@ApiModelProperty(name = "type", value = "产品类型", dataType = "query")
private String type;
}
Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}"
http://localhost:8080/v2/api-docs
多环境配置
application-dev.properties:开发环境
application-test.properties:演示环境
application-prod.properties:生产环境
# 运行演示环境命令
java -jar spring-boot-example-0.0.1-SNAPSHOT --spring.profiles.active=test
spring:
profiles:
# 默认使用开发环境
active: dev
多环境下的日志配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="maxsize" value="30MB" />
<property name="maxdays" value="90" />
<springProperty scope="context" name="logdir" source="resources.logdir"/>
<springProperty scope="context" name="appname" source="resources.appname"/>
<springProperty scope="context" name="basepackage" source="resources.basepackage"/>
<appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
<pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{36} - %msg%n</pattern>
</pattern>
</layout>
</appender>
<appender name="fileLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${logdir}/${appname}.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${logdir}/${appname}.%d{yyyy-MM-dd}.log</FileNamePattern>
<maxHistory>${maxdays}</maxHistory>
<totalSizeCap>${maxsize}</totalSizeCap>
</rollingPolicy>
<encoder>
<charset>UTF-8</charset>
<pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="consoleLog"/>
</root>
<logger name="${basepackage}" level="DEBUG" additivity="false">
<appender-ref ref="consoleLog"/>
</logger>
</springProfile>
<springProfile name="test">
<root level="WARN">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</root>
<logger name="${basepackage}" level="INFO" additivity="false">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</logger>
</springProfile>
<springProfile name="prod">
<root level="ERROR">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</root>
</springProfile>
</configuration>
#应用配置
resources:
# log文件写入地址
logdir: logs/
# 应用名称
appname: spring-boot-example
# 日志打印的基础扫描包
basepackage: com.spring.demo.springbootexample
@RequestMapping("/logger")
@ResponseBody
public WebResult logger() {
logger.trace("日志输出 {}", "trace");
logger.debug("日志输出 {}", "debug");
logger.info("日志输出 {}", "info");
logger.warn("日志输出 {}", "warn");
logger.error("日志输出 {}", "error");
return "00";
}
加载自定义配置
@Component
@PropertySource(value = {"classpath:application.yml"}, encoding = "utf-8")
public class Config {
@Value("${resources.midpHost}")
private String midpHost;
public String getMidpHost() {
return midpHost;
}
}
全局异常处理器
@ControllerAdvice
public class GlobalExceptionResolver {
Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public WebResult exceptionHandle(HttpServletRequest req, Exception ex) {
ex.printStackTrace();
logger.error("未知异常", ex);
return WebResult.error(ERRORDetail.RC_0401001);
}
}